package com.learning.platform.service;

import com.learning.platform.dto.CategoryResponse;
import com.learning.platform.entity.Category;
import com.learning.platform.repository.CategoryRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {
    
    private final CategoryRepository categoryRepository;
    
    public CategoryService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }
    
    /**
     * 获取所有顶级分类
     */
    public List<CategoryResponse> getTopCategories() {
        List<Category> categories = categoryRepository.findByParentIdIsNullOrderBySortOrder();
        return categories.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取分类的子分类
     */
    public List<CategoryResponse> getSubCategories(Long parentId) {
        List<Category> categories = categoryRepository.findByParentIdOrderBySortOrder(parentId);
        return categories.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取所有分类（树形结构）
     */
    public List<CategoryResponse> getAllCategoriesTree() {
        List<CategoryResponse> topCategories = getTopCategories();
        
        for (CategoryResponse category : topCategories) {
            List<CategoryResponse> children = getSubCategories(category.getId());
            category.setChildren(children);
        }
        
        return topCategories;
    }
    
    /**
     * 根据ID获取分类
     */
    public CategoryResponse getCategoryById(Long id) {
        Category category = categoryRepository.findById(id).orElse(null);
        return category != null ? convertToResponse(category) : null;
    }
    
    /**
     * 转换为响应DTO
     */
    private CategoryResponse convertToResponse(Category category) {
        CategoryResponse response = new CategoryResponse();
        response.setId(category.getId());
        response.setName(category.getName());
        response.setDescription(category.getDescription());
        response.setParentId(category.getParentId());
        response.setSortOrder(category.getSortOrder());
        response.setCreatedAt(category.getCreatedAt());
        return response;
    }
}


